// Copyright (C) Microsoft Corporation. All Rights Reserved.
// This code released under the terms of the
// Microsoft Limited Public License (Ms-LPL).

using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading;
using System.CodeDom.Compiler;
using System.Configuration;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using Microsoft.VisualStudio.IntelliTrace;
using Microsoft.VisualStudio.Samples.IHandlers;

namespace Microsoft.VisualStudio.Samples
{
    public class IntelliTraceReader : IDisposable
	{

        private IntelliTraceProcess Process {get; set;}
        private ChainFormatter Formatter {get; set;}
        private IntelliTraceFile LogFile {get;set;}

		#region Constructors

		public IntelliTraceReader(string logFileName)
		{
            // Require a log file name.
            if (logFileName == null)
			{
				throw new Exception("Log file not found.");
			}

			IntelliTraceFile logFile = null;
			// Open the trace debug log file and create a trace process from it.
			try
			{
                logFile = new IntelliTraceFile(logFileName);
			}
			catch (Exception ex)
			{
                throw new Exception(String.Format("Unable to open log file '{0}'. {1}", logFileName, ex.Message), ex);
			}
		
			IList<IntelliTraceProcess> processes = logFile.Processes;
			Debug.Assert(processes.Count == 1);
            Process = processes[0];
            LogFile = logFile;
            Formatter = new ChainFormatter(Process);
		}

		#endregion

		public bool Execute()
		{
			
			if (!Formatter.Dump(LogFile, Process))
				return false;
			
			return true;
		}

        public void Dispose()
        {
            LogFile.Dispose();
        }

        public void AddCheckpointEventHandler(CheckpointChainHandler handler)
        {
            Formatter.AddCheckpointEventHandler(handler);
        }
        public void AddDiagnosticEventHandler(DiagnosticChainHandler handler)
        {
            Formatter.AddDiagnosticEventHandler(handler);
        }
        public void AddTestEventHandler(TestChainHandler handler)
        {
            Formatter.AddTestEventHandler(handler);
        }
        public void AddMetaDataEventHandler(MetadataChainHandler handler)
        {
            Formatter.AddMetaDataEventHandler(handler);
        }
        public void AddProcessEventHandler(ProcessChainHandler handler)
        {
            Formatter.AddProcessEventHandler(handler);
        }
        public void AddThreadEventHandler(ThreadChainHandler handler)
        {
            Formatter.AddThreadEventHandler(handler);
        }

        
    }
}
